//
//  LZSelectDateView.m
//  laziz_Merchant
//
//  Created by ZhaoDongBo on 2016/12/20.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZSelectDateView.h"
#import "Masonry.h"

@interface LZSelectDateView() <UIPickerViewDelegate, UIPickerViewDataSource>
{
    NSMutableArray *yearArray;
    NSArray *monthArray;
    NSMutableArray *DaysArray;
    NSMutableArray *hoursArray;
    NSMutableArray *minutesArray;
    
    NSInteger selectedYearRow;
    NSInteger selectedMonthRow;
    NSInteger selectedDayRow;
}

@property (nonatomic, strong) UIView * maskView;
@property (nonatomic, strong) UIView * contentView;

@end

@implementation LZSelectDateView

- (instancetype)initWithFrame:(CGRect)frame andSelectType:(SELECT_TYPE)type
{
    self = [super initWithFrame:frame];
    if (self) {
        self.type = type;
        [self setup];
    }
    return self;
}

- (void)setup {
    
    self.userInteractionEnabled = YES;
    
    [self addSubview:self.maskView];
    [self addSubview:self.contentView];
    [self.contentView addSubview:self.pickView];
    [self.contentView addSubview:self.cancelButton];
    [self.contentView addSubview:self.confirmButton];
    
    WS(weakSelf);
    [self.cancelButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(weakSelf.confirmButton.mas_leading);
        make.height.mas_equalTo(45);
    }];
    [self.confirmButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH/2.0);
        make.height.mas_equalTo(45);
    }];
    
    
    if ([[LZLanguageManager shareInstance] getLanguageType] == LanguageType_Ar) {

        // PickerView -  Years data
        
        yearArray = [NSMutableArray arrayWithArray:@[@"٢٠١٦", @"٢٠١٧", @"٢٠١٨",@"٢٠١٩",@"٢٠٢٠",@"٢٠٢١",@"٢٠٢٢",@"٢٠٢٣",@"٢٠٢٤",@"٢٠٢٥",
                                                     @"٢٠٢٦", @"٢٠٢٧", @"٢٠٢٨",@"٢٠٢٩",@"٢٠٣٠",@"٢٠٣١",@"٢٠٣٢",@"٢٠٣٣",@"٢٠٣٤",@"٢٠٣٥",
                                                     @"٢٠٣٦", @"٢٠٣٧", @"٢٠٣٨",@"٢٠٣٩",@"٢٠٤٠",@"٢٠٤١",@"٢٠٤٢",@"٢٠٤٣",@"٢٠٤٤",@"٢٠٤٥",
                                                     @"٢٠٤٦", @"٢٠٤٧", @"٢٠٤٨",@"٢٠٤٩",@"٢٠٥٠"]];
        
        // PickerView -  Months data
        monthArray = @[@"٠١",@"٠٢",@"٠٣",@"٠٤",@"٠٥",@"٠٦",@"٠٧",@"٠٨",@"٠٩",@"١٠",@"١١",@"١٢"];
        // PickerView -  Hours data
        hoursArray = [NSMutableArray arrayWithArray:@[@"٠٠",@"٠١",@"٠٢",@"٠٣",@"٠٤",@"٠٥",@"٠٦",@"٠٧",@"٠٨",@"٠٩",@"١٠",@"١١",
                                                      @"١٢",@"١٣",@"١٤",@"١٥",@"١٦",@"١٧",@"١٨",@"١٩",@"٢٠",@"٢١",@"٢٢",@"٢٣"]];
        
        minutesArray = [NSMutableArray arrayWithArray:@[@"٠٠",@"٠١",@"٠٢",@"٠٣",@"٠٤",@"٠٥",@"٠٦",@"٠٧",@"٠٨",@"٠٩",
                                                        @"١٠",@"١١",@"١٢",@"١٣",@"١٤",@"١٥",@"١٦",@"١٧",@"١٨",@"١٩",
                                                        @"٢٠",@"٢١",@"٢٢",@"٢٣",@"٢٤",@"٢٥",@"٢٦",@"٢٧",@"٢٨",@"٢٩",
                                                        @"٣٠",@"٣١",@"٣٢",@"٣٣",@"٣٤",@"٣٥",@"٣٦",@"٣٧",@"٣٨",@"٣٩",
                                                        @"٤٠",@"٤١",@"٤٢",@"٤٣",@"٤٤",@"٤٥",@"٤٦",@"٤٧",@"٤٨",@"٤٩",
                                                        @"٥٠",@"٥١",@"٥٢",@"٥٣",@"٥٤",@"٥٥",@"٥٦",@"٥٧",@"٥٨",@"٥٩"]];
        
        // PickerView -  days data
        DaysArray = [NSMutableArray arrayWithArray:@[@"٠١",@"٠٢",@"٠٣",@"٠٤",@"٠٥",@"٠٦",@"٠٧",@"٠٨",@"٠٩",@"١٠",
                                                     @"١١",@"١٢",@"١٣",@"١٤",@"١٥",@"١٦",@"١٧",@"١٨",@"١٩",@"٢٠",
                                                     @"٢١",@"٢٢",@"٢٣",@"٢٤",@"٢٥",@"٢٦",@"٢٧",@"٢٨",@"٢٩",@"٣٠",@"٣١"]];
    } else {

        // PickerView -  Years data
        
        yearArray = [[NSMutableArray alloc]init];
        for (int i = 2016; i <= 2050 ; i++)
        {
            [yearArray addObject:[NSString stringWithFormat:@"%d",i]];
        }
        
        // PickerView -  Months data
        monthArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
        
        // PickerView -  days data
        DaysArray = [[NSMutableArray alloc]init];
        for (int i = 1; i <= 31; i++)
        {
            [DaysArray addObject:[NSString stringWithFormat:@"%02d",i]];
        }
        
        hoursArray = [NSMutableArray array];
        for (int i = 0; i <= 23; i++) {
            // PickerView -  Hours data
            [hoursArray addObject:[NSString stringWithFormat:@"%02d", i]];
        }
        
        // PickerView -  Hours data
        minutesArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < 60; i++)
        {
            [minutesArray addObject:[NSString stringWithFormat:@"%02d",i]];
        }
    }
}

- (void)showTime {

    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    // Get Current Year
    [formatter setDateFormat:@"yyyy"];
    NSString *currentyearString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"年yyyy:%@", currentyearString);
    
    // Get Current  Month
    [formatter setDateFormat:@"MM"];
    NSString *currentMonthString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"月MM:%@", currentMonthString);
    
    // Get Current  Date
    [formatter setDateFormat:@"dd"];
    NSString *currentDateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"日dd:%@", currentDateString);
    
    // Get Current  Hour
    [formatter setDateFormat:@"HH"];
    NSString *currentHourString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"时HH:%@", currentHourString);
    
    // Get Current  Minutes
    [formatter setDateFormat:@"mm"];
    NSString *currentMinutesString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"分mm:%@", currentMinutesString);
    
    // PickerView - Default Selection as per current Date

    if (self.type == SELECT_TYPE_DATE) {
        NSInteger yearIndex = [yearArray indexOfObject:currentyearString];
        NSInteger monthIndex = [monthArray indexOfObject:currentMonthString];
        NSInteger dayIndex = [DaysArray indexOfObject:currentDateString];
        
        [self.pickView selectRow:yearIndex inComponent:0 animated:YES];
        [self.pickView selectRow:monthIndex inComponent:1 animated:YES];
        [self.pickView selectRow:dayIndex inComponent:2 animated:YES];
        
        selectedYearRow = yearIndex;
        selectedMonthRow = monthIndex;
        selectedDayRow = dayIndex;
        [self.pickView reloadAllComponents];
    }
    else {
        [self.pickView selectRow:[hoursArray indexOfObject:currentHourString] inComponent:0 animated:YES];
        [self.pickView selectRow:[minutesArray indexOfObject:currentMinutesString] inComponent:1 animated:YES];
    }
}

- (void)showDateView:(NSString *)strDate {
    
    NSString *currentyearString = nil;
    NSString *currentMonthString = nil;
    NSString *currentDateString= nil;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

    NSDate *date = nil;

    if (strDate) {
        [formatter setDateFormat:@"dd-MM-yyyy"];
        date = [formatter dateFromString:strDate];
    }
    else {
        date = [NSDate date];
    }
    
    // Get Current Year
    [formatter setDateFormat:@"yyyy"];
    currentyearString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"年yyyy:%@", currentyearString);
    
    // Get Current  Month
    [formatter setDateFormat:@"MM"];
    currentMonthString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"月MM:%@", currentMonthString);
    
    // Get Current  Date
    [formatter setDateFormat:@"dd"];
    currentDateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
    DLog(@"日dd:%@", currentDateString);
    
    NSInteger yearIndex = [yearArray indexOfObject:currentyearString];
    NSInteger monthIndex = [monthArray indexOfObject:currentMonthString];
    NSInteger dayIndex = [DaysArray indexOfObject:currentDateString];
    
    [self.pickView selectRow:yearIndex inComponent:0 animated:YES];
    [self.pickView selectRow:monthIndex inComponent:1 animated:YES];
    [self.pickView selectRow:dayIndex inComponent:2 animated:YES];
    
    selectedYearRow = yearIndex;
    selectedMonthRow = monthIndex;
    selectedDayRow = dayIndex;
    [self.pickView reloadAllComponents];
    
    [self showSelectView];
}

- (void)showTimeView:(NSString *)time andTimeType:(SELECT_TIME_TYPE)timeType {
    
    NSString *currentHourString = nil;
    NSString *currentMinutesString = nil;
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    NSDate *date = nil;
    
    if (time) {
        [formatter setDateFormat:@"HH:mm"];
        date = [formatter dateFromString:time];
        
        // Get Current  Hour
        [formatter setDateFormat:@"HH"];
        currentHourString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
        DLog(@"时HH:%@", currentHourString);
        
        // Get Current  Minutes
        [formatter setDateFormat:@"mm"];
        currentMinutesString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
        DLog(@"分mm:%@", currentMinutesString);
    }
    else {
        if (timeType == SELECT_TIME_TYPE_Start) {
            currentHourString = [hoursArray firstObject];
            currentMinutesString = [minutesArray firstObject];
        }
        else if (timeType == SELECT_TIME_TYPE_End) {
            currentHourString = [hoursArray lastObject];
            currentMinutesString = [minutesArray lastObject];
        }
        else if (timeType == SELECT_TIME_TYPE_Now) {
            date = [NSDate date];

            // Get Current  Hour
            [formatter setDateFormat:@"HH"];
            currentHourString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
            DLog(@"时HH:%@", currentHourString);
            
            // Get Current  Minutes
            [formatter setDateFormat:@"mm"];
            currentMinutesString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
            DLog(@"分mm:%@", currentMinutesString);
        }
    }
    
    [self.pickView selectRow:[hoursArray indexOfObject:currentHourString] inComponent:0 animated:NO];
    [self.pickView selectRow:[minutesArray indexOfObject:currentMinutesString] inComponent:1 animated:NO];
    
    [self showSelectView];
}

#pragma mark - UIPickerViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (self.type == SELECT_TYPE_DATE) {
        if (component == 0)
        {
            selectedYearRow = row;
            [self.pickView reloadAllComponents];
        }
        else if (component == 1)
        {
            selectedMonthRow = row;
            [self.pickView reloadComponent:2];
        }
        else if (component == 2)
        {
            selectedDayRow = row;
            [self.pickView reloadAllComponents];
        }
    }
}

#pragma mark - UIPickerViewDatasource

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {
    
    // Custom View created for each component
    
    UILabel *pickerLabel = (UILabel *)view;
    
    if (pickerLabel == nil) {
        CGRect frame = CGRectMake(0.0, 0.0, 50, 60);
        pickerLabel = [[UILabel alloc] initWithFrame:frame];
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont systemFontOfSize:15.0f]];
        pickerLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0];
        pickerLabel.textColor = [UIColor blackColor];
    }
    
    if (self.type == SELECT_TYPE_DATE) {
        
        if (component == 0) {
            pickerLabel.text =  [yearArray objectAtIndex:row]; // Year
        }
        else if (component == 1) {
            pickerLabel.text =  [monthArray objectAtIndex:row];  // Month
        }
        else if (component == 2) {
            pickerLabel.text =  [DaysArray objectAtIndex:row]; // Date
        }
    } else {
        
        if (component == 0) {
            pickerLabel.text =  [hoursArray objectAtIndex:row]; // Hours
        }
        else if (component == 1) {
            pickerLabel.text =  [minutesArray objectAtIndex:row]; // Mins
        }
    }

    return pickerLabel;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (self.type == SELECT_TYPE_DATE) {
        return 3;
    } else {
        return 2;
    }
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (self.type == SELECT_TYPE_DATE) {
        if (component == 0) {
            return [yearArray count];
        }
        else if (component == 1) {
            return [monthArray count];
        }
        else { // day
            if (selectedMonthRow == 0 || selectedMonthRow == 2 || selectedMonthRow == 4 || selectedMonthRow == 6 || selectedMonthRow == 7 || selectedMonthRow == 9 || selectedMonthRow == 11) {
                return 31;
            }
            else if (selectedMonthRow == 1) {
                
                int yearint = [[yearArray objectAtIndex:selectedYearRow] intValue];
                if(((yearint %4==0)&&(yearint %100!=0))||(yearint %400==0)){
                    return 29;
                } else {
                    return 28; // or return 29
                }
                
            } else {
                
                return 30;
            }
        }
        
    } else {
        
        if (component == 0) { // hour
            return 24;
        }
        else { // min
            return 60;
        }
    }
}

- (void)showSelectView
{
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    
    WS(weakSelf);
    const float shareViewHeight = 300;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        weakSelf.maskView.alpha = 0.3f;
        
        CGRect frame    = weakSelf.contentView.frame;
        frame.origin.y  = SCREEN_HEIGHT-shareViewHeight;
        weakSelf.contentView.frame = frame;
        
    } completion:^(BOOL finished) {
    }];
}

- (void)hideSelectView
{
    WS(weakSelf);
    
    [UIView animateWithDuration:0.3 animations:^{
        
        weakSelf.maskView.alpha = 0.0f;
        
        CGRect frame    = weakSelf.contentView.frame;
        frame.origin.y  = SCREEN_HEIGHT+40;
        weakSelf.contentView.frame = frame;
        
    } completion:^(BOOL finished) {
        
        [self removeFromSuperview];
    }];
}

- (void)cancelButton:(id)sender {
    [self hideSelectView];
}

- (void)confirmButton:(id)sender {
    NSString * valueStr = nil;
    if (self.type == SELECT_TYPE_DATE) {
        valueStr = [NSString stringWithFormat:@"%@-%@-%@",
                    [yearArray objectAtIndex:[self.pickView selectedRowInComponent:0]],
                    [monthArray objectAtIndex:[self.pickView selectedRowInComponent:1]],
                    [DaysArray objectAtIndex:[self.pickView selectedRowInComponent:2]]];
    }
    else {
        valueStr = [NSString stringWithFormat:@"%@:%@",
                    [hoursArray objectAtIndex:[self.pickView selectedRowInComponent:0]],
                    [minutesArray objectAtIndex:[self.pickView selectedRowInComponent:1]]];
    }

    if(self.selectValueBlock) {
        self.selectValueBlock(valueStr);
    }
                    
    [self hideSelectView];
}

- (UIPickerView *)pickView {
    if (_pickView == nil) {
        _pickView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 255)];
        _pickView.backgroundColor = UIColorFromRGB(0xffffff, 1);
        _pickView.delegate = self;
        _pickView.dataSource = self;
    }
    return _pickView;
}

- (UIView *)maskView {
    
    if (_maskView == nil) {
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _maskView.backgroundColor = [UIColor blackColor];
        _maskView.userInteractionEnabled = YES;
        _maskView.alpha = 0;
        
        UITapGestureRecognizer *tapMaskView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSelectView)];
        [_maskView addGestureRecognizer:tapMaskView];
    }
    
    return _maskView;
}

- (UIView *)contentView {
    if (_contentView == nil) {
        _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 300)];
        _contentView.backgroundColor = UIColorFromRGB(0xffffff, 1);
    }
    
    return _contentView;
}

- (UIButton *)cancelButton {
    
    if (_cancelButton == nil) {
        _cancelButton = [[UIButton alloc] init];
        _cancelButton.backgroundColor = UIColorFromRGB(0x333333, 1);
        [_cancelButton setTitle:LZLocalizedString(@"cancel", @"") forState:UIControlStateNormal];
        [_cancelButton setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _cancelButton;
}

- (UIButton *)confirmButton {
    if (_confirmButton == nil) {
        _confirmButton = [[UIButton alloc] init];
        _confirmButton.backgroundColor = UIColorFromRGB(0x33a928, 1);
        [_confirmButton setTitle:LZLocalizedString(@"confirm", nil) forState:UIControlStateNormal];
        [_confirmButton setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _confirmButton;
}

@end
